package com.jinzhi.jzweb.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jinzhi.api.exception.IFastApiException;
import com.jinzhi.common.base.CoreServiceImpl;
import com.jinzhi.common.type.EnumErrorCode;
import com.jinzhi.common.utils.*;
import com.jinzhi.jzapi.utils.MD5Util;
import com.jinzhi.jzweb.pojo.UserVo;
import com.jinzhi.jzweb.service.IndexService;
import com.jinzhi.sms.config.SmsBasicConfigProperties;
import com.jinzhi.sys.dao.UserDao;
import com.jinzhi.sys.domain.UserDO;
import org.springframework.cache.Cache;
import org.springframework.stereotype.Service;

/***
 * @author C
 * @Date 2023/12/7
 * @Description: 登录注册业务层
 * @Version 1.0
 */
@Service
public class IndexServiceImpl extends CoreServiceImpl<UserDao, UserDO> implements IndexService {
    private SmsBasicConfigProperties properties;
    private Cache cache;

    private static final String O_REG_SMS_PREFIX = "ORTHER_REG_";



    /**
     * 注册
     *
     * @param userVo
     */
    @Override
    public Integer register(UserVo userVo) {
        // 判断
        if (userVo==null){
             //Result.build(EnumErrorCode.userLoginFai1l4.getCode(),EnumErrorCode.userLoginFai1l4.getMsg());
            throw new IFastApiException("参数异常,请重新输入参数");
        }
        // 校验账号是否存在
        EntityWrapper<UserDO> wrapper = new EntityWrapper<>();
        wrapper.eq("mobile",userVo.getMobile()).eq("is_deleted",0);
        int count = this.selectCount(wrapper);
        if (count>0){
            throw new IFastApiException("用户已存在，请登录");
        }

        //定义UserDo
        UserDO userDO = new UserDO();
        userDO.setName(userVo.getName());
        userDO.setUsername(userVo.getName());
        userDO.setStatus(1);
        //判断类型 - 3教师  5学生
        if (userVo.getType().equals(3)){
            userDO.setType(userVo.getType());
            userDO.setStudentId(userVo.getNum());
        }else if (userVo.getType().equals(5)){
            userDO.setType(userVo.getType());
            userDO.setStudentId(userVo.getNum());
        }else {
            throw new IFastApiException("账号类型错误");
        }
        // 手机号
        userDO.setMobile(userVo.getMobile());
        // 验证码  ORTHER_REG_
//        String key = properties.getCacheKeyPrefix() + ":" +  O_REG_SMS_PREFIX + ":" + userVo.getMobile();
//        String code = (String) cache.get(key).get();
        // 获取缓存中的验证码
        String code1 = (String) EhCacheUtil.get(userVo.getMobile()+"wx");
        // 校验验证码是否正确
        if (!code1.equals(userVo.getCode())){
            Result.build(EnumErrorCode.userLoginFai1l1.getCode(),EnumErrorCode.userLoginFai1l1.getMsg());
        }

        // 密码
        String salt = UUIDUtils.get();
        String encodePasswd = PasswdUtils.get(userVo.getPassword(), salt);

        userDO.setSalt(salt);

        userDO.setPassword(MD5Utils.string2MD5(userVo.getPassword()));

        // 注册
        return this.baseMapper.insert(userDO);
    }
}
